<template>
  <!-- 问题处理配置表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '600px' : '750px'"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="110"
        v-show="!props.isReadonly"
      >
        <div>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="问题处理方案"
                prop="exceptionSolvingScheme"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.exceptionSolvingScheme"
                  placeholder="请输入问题处理方案"
                  clearable
                />
                <span v-else>{{ formData.exceptionSolvingScheme }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="描述" prop="remarks" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入描述"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="问题类型"
                prop="exceptionSolvingType"
                style="width: 100%"
              >
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.exceptionSolvingType"
                  placeholder="请选择问题类型"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'ApproachType'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="Number(item.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group
                  v-model="formData.enabled"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        title=""
        :column="2"
        size="large"
        style="margin-bottom: 20px"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">问题处理方案</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.exceptionSolvingScheme }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">问题类型</div>
          </template>
          {{
            dictionaryStore.filterDictName(
              "ApproachType",
              formData.exceptionSolvingType
            )
          }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">描述</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <h4 class="mb-[20px] mt-[20px]">工单选择</h4>
      <el-card shadow="never" class="table-container">
        <el-checkbox-group
          v-model="checkedCities"
          style="max-height: 400px; overflow-y: auto"
        >
          <el-checkbox
            style="display: block"
            v-for="item in dictionaryStore.filterDictList('problemTicket')"
            :key="item.value"
            :disabled="props.isReadonly"
            :label="item.value"
          >
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSEXCEPTIONSOLVINGSETTINGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  exceptionSolvingScheme: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  exceptionSolvingType: "",
  details: [
    // {
    //   id: "",
    //   exceptionSolvingSchemeId: "",
    //   exceptionSolvingWork: "",
    //   version: "",
    //   remarks: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    //   enabled: "",
    //   deleted: "",
    // },
  ],
});

/** rules规则 */
const rules = reactive({
  exceptionSolvingScheme: [
    { required: true, message: "请输入问题处理方案", trigger: "blur" },

    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
  sonexceptionSolvingSchemeId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonexceptionSolvingWork: [],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonenabled: [],
  exceptionSolvingType: [
    { required: true, message: "请选择问题类型", trigger: "change" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  exceptionSolvingSchemeId: "",
  exceptionSolvingWork: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.id = "";
  formData.exceptionSolvingScheme = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.exceptionSolvingType = "";
  checkedCities.value = [];
}

const loading = ref(false);

/** 问题处理配置保存提交 */
function handleSubmit() {
  checkedList();
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // if (formData.details.length == 0) {
      //   ElMessage.error("请选择至少一项问题工单！");
      //   return;
      // }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmsexceptionsolvingsetting/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/qms/qmsexceptionsolvingsetting/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  // 多选框赋值
  checkedCities.value = [];
  checkedCities.value = formData.details.map(function (item) {
    return String(item.exceptionSolvingWork);
  });
}
// 工单选择
const checkedCities: any = ref([]);
// 工单赋值
const checkedList = () => {
  formData.details = [];
  checkedCities.value.forEach((item) => {
    formData.details.push({
      exceptionSolvingSchemeId: formData.id ? formData.id : "",
      exceptionSolvingWork: item,
    });
  });
};

onMounted(() => {
  console.log(dictionaryStore.filterDictList("problemTicket"));
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 120px;
}
</style>
